<template>
  <div class="edit-issue">
    <div class="page-header">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item :to="{ path: '/issues' }">问题管理</el-breadcrumb-item>
        <el-breadcrumb-item :to="{ path: `/issues/${$route.params.id}` }">问题详情</el-breadcrumb-item>
        <el-breadcrumb-item>编辑问题</el-breadcrumb-item>
      </el-breadcrumb>
      <h1>编辑问题</h1>
    </div>

    <div class="content-container">
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="120px"
        class="issue-form"
      >
        <el-row :gutter="24">
          <el-col :span="16">
            <el-form-item label="问题标题" prop="title">
              <el-input
                v-model="form.title"
                placeholder="请输入问题标题"
                maxlength="100"
                show-word-limit
              />
            </el-form-item>

            <el-form-item label="问题描述" prop="description">
              <el-input
                v-model="form.description"
                type="textarea"
                :rows="6"
                placeholder="请详细描述问题..."
                maxlength="1000"
                show-word-limit
              />
            </el-form-item>

            <el-form-item label="关联项目" prop="projectId">
              <el-select
                v-model="form.projectId"
                placeholder="请选择关联项目"
                style="width: 100%"
                @change="() => { form.taskId = null }"
              >
                <el-option
                  v-for="project in projects"
                  :key="project.id"
                  :label="project.name"
                  :value="project.id"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="关联任务" prop="taskId">
              <el-select
                v-model="form.taskId"
                placeholder="请选择关联任务（可选）"
                style="width: 100%"
                clearable
              >
                <el-option
                  v-for="task in tasks"
                  :key="task.id"
                  :label="task.title"
                  :value="task.id"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="问题类型" prop="type">
              <el-select v-model="form.type" placeholder="请选择问题类型" style="width: 100%">
                <el-option label="缺陷" value="bug" />
                <el-option label="功能请求" value="feature" />
                <el-option label="改进" value="improvement" />
                <el-option label="任务" value="task" />
              </el-select>
            </el-form-item>

            <el-form-item label="优先级" prop="priority">
              <el-select v-model="form.priority" placeholder="请选择优先级" style="width: 100%">
                <el-option label="紧急" value="urgent" />
                <el-option label="高" value="high" />
                <el-option label="中" value="medium" />
                <el-option label="低" value="low" />
              </el-select>
            </el-form-item>

            <el-form-item label="状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择状态" style="width: 100%">
                <el-option label="待处理" value="open" />
                <el-option label="处理中" value="in_progress" />
                <el-option label="已解决" value="resolved" />
                <el-option label="已关闭" value="closed" />
                <el-option label="重新打开" value="reopened" />
              </el-select>
            </el-form-item>

            <el-form-item label="指派人" prop="assigneeId">
              <el-select
                v-model="form.assigneeId"
                placeholder="请选择指派人（可选）"
                style="width: 100%"
                clearable
              >
                <el-option
                  v-for="user in users"
                  :key="user.id"
                  :label="user.username"
                  :value="user.id"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="截止日期" prop="dueDate">
              <el-date-picker
                v-model="form.dueDate"
                type="date"
                placeholder="请选择截止日期（可选）"
                style="width: 100%"
                :disabled-date="(time: Date) => time.getTime() < Date.now() - 8.64e7"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item>
          <el-button type="primary" @click="handleSubmit" :loading="loading">
            保存修改
          </el-button>
          <el-button @click="handleCancel">取消</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'

const router = useRouter()
const route = useRoute()
const formRef = ref<FormInstance>()
const loading = ref(false)

// 表单数据
const form = reactive({
  title: '',
  description: '',
  projectId: null as number | null,
  taskId: null as number | null,
  type: '',
  priority: '',
  status: '',
  assigneeId: null as number | null,
  dueDate: null as Date | null
})

// 表单验证规则
const rules: FormRules = {
  title: [
    { required: true, message: '请输入问题标题', trigger: 'blur' },
    { min: 5, max: 100, message: '标题长度应在 5 到 100 个字符之间', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入问题描述', trigger: 'blur' },
    { min: 10, message: '描述至少需要 10 个字符', trigger: 'blur' }
  ],
  projectId: [
    { required: true, message: '请选择关联项目', trigger: 'change' }
  ],
  type: [
    { required: true, message: '请选择问题类型', trigger: 'change' }
  ],
  priority: [
    { required: true, message: '请选择优先级', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 项目列表
const projects = ref([
  { id: 1, name: '项目管理系统' },
  { id: 2, name: '电商平台' },
  { id: 3, name: '移动应用' }
])

// 任务列表
const tasks = ref([
  { id: 1, title: '用户登录功能开发', projectId: 1 },
  { id: 2, title: '数据库设计', projectId: 1 },
  { id: 3, title: '商品管理模块', projectId: 2 }
])

// 用户列表
const users = ref([
  { id: 1, username: '张三' },
  { id: 2, username: '李四' },
  { id: 3, username: '王五' }
])

// 加载问题数据
const loadIssue = async () => {
  const issueId = route.params.id
  // 模拟加载问题数据
  const mockIssue = {
    id: Number(issueId),
    title: '用户登录页面样式错乱',
    description: '在Chrome浏览器中，登录页面的样式显示不正常，按钮位置偏移。',
    projectId: 1,
    taskId: 1,
    type: 'bug',
    priority: 'high',
    status: 'open',
    assigneeId: 2,
    dueDate: new Date('2024-02-01')
  }
  
  Object.assign(form, mockIssue)
}

// 项目变化处理
// const handleProjectChange = (projectId: number) => {
//   // 过滤任务列表
//   form.taskId = null
// }

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    loading.value = true
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    ElMessage.success('问题修改成功')
    router.push(`/issues/${route.params.id}`)
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    loading.value = false
  }
}

// 取消编辑
const handleCancel = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要取消编辑吗？未保存的修改将会丢失。',
      '确认取消',
      {
        confirmButtonText: '确定',
        cancelButtonText: '继续编辑',
        type: 'warning'
      }
    )
    router.push(`/issues/${route.params.id}`)
  } catch {
    // 用户取消操作
  }
}

onMounted(() => {
  loadIssue()
})
</script>

<style scoped>
.edit-issue {
  padding: 0;
}

.page-header {
  margin-bottom: 24px;
}

.page-header h1 {
  margin: 16px 0 0 0;
  font-size: 24px;
  color: #333;
}

.content-container {
  background: #fff;
  padding: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.issue-form {
  max-width: 1200px;
}

.el-form-item {
  margin-bottom: 24px;
}
</style>